// pages/detail/detail.js
const app = getApp()
var core = require('../../utils/core.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
      id:56, 
      data:{
        title:'',
        desc:'',
        read_num:0,
      },
      is_need_pay:1,
      pay_type:1,
      from:1,
      qrcodeFlag:0,
      qrcode_img:'http://wqq103910.oss-cn-hangzhou.aliyuncs.com/images/3/2020/08/M7q7P5bqR7TeMeqPE7e8A3MpiBI7OR.jpg',
      hideModal: true, //模态框的状态  true-隐藏  false-显示
      animationData: {},//

      pag_flag:false,
      pay_fee:0,
      radioItems: [
        {name: '微信支付', value: '1',checked: 'true',img:'/static/images/news/wx.png'},
        {name: '免费置换', value: '3',img:'/static/images/news/change.png'}
      ],
      userinfo:{},
      MyProject:[],
      MyProjectId:0,
      MyProjectArr:[],
      MyProjectKey:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options != null&& options!= undefined&&options.openid) {
      wx.setStorageSync('otheropenid', options.openid)  
    }
    if(options.id){
      this.setData({id:options.id})
    }
    
    if(options.scene){
      const scene = decodeURIComponent(options.scene)
      this.setData({id:scene})
    }
    
    this.getInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.GetUserInfo();
    this.getMyProjectList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getInfo()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return this.share()
  },
    /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    return this.share()
  },
  share:function(){
    //this.hideModal()
    return {
      title:  this.data.data.title,
      path: '/pages/project/detail?id=' + this.data.id+'&openid='+wx.getStorageSync('openid1'),
      imageUrl:  app.globalData.shareimg//自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4。
    }
  },
  to_main:function(){
    wx.navigateTo({
      url:"/pages/index/index"
    })
  },
  getInfo:function(){
    //this.data=this.data1
    
    var self=this
    core.post("ProjectDetail",{id:self.data.id},function(res){
      if(res.code==1){
          self.setData({
            data:res.data,
            is_need_pay:res.data.is_need_pay,
            pay_fee:res.data.fee
          })
          
      }
      wx.stopPullDownRefresh()
    })
    
},
  /**
   * 海报生成
   */
  create_qrcode:function(){
    this.hideModal()
    wx.showLoading({
      title: '生成中',
    })
    var self=this
    core.post("Qrcode",{id:self.data.id,op:'create',type:1},function(res){
      if(res.code==1){
        self.setData({qrcode_img:res.data.qrcode,qrcodeFlag:1})
      }
      wx.hideLoading();
    })
  },
  /**
   * 海报保存
   */
  save_qrcode:function(){
    var self=this
    wx.getImageInfo({
      src: self.data.qrcode_img,
      success: function (ret) {
          var path = ret.path;
          wx.saveImageToPhotosAlbum({
              filePath: path,
              success(result) {
                wx.showToast({
                  'title':'保存成功',
                  'icon':'success'
                })
              }
          })
      }
    })
  },
  /**
   * 海报取消
   */
  cancel_qrcode:function(){
    this.setData({qrcodeFlag:0})
  },
  /**
   * 复制微信号
   */
  copy:function(){
    var self=this
    wx.setClipboardData({
          data: self.data.data.wx,
          success: function (res) {
            // wx.showModal({
            //     title: '提示',
            //     content: '复制成功',
            //     });
            }
      })
  },
  Location:function(){
    var self=this
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success (res) {
        const latitude = self.data.data.lat*1
        const longitude = self.data.data.lng*1
        wx.openLocation({
          latitude,
          longitude,
          scale: 18
        })
      }
     })
  },
  readmore:function(){
    var self=this
    
    //微信支付
    if(self.data.pay_type==1){
        self.readmore_confirm()
    }
    //置换
    if(self.data.pay_type==3){
      
      if(self.data.userinfo.change_num<=0){
        wx.showToast({
          'title':'置换次数不足',
          'icon':'none'
        })
        return;
      }
     
      wx.showModal({
        title: '提示',
        content: '确认进行项目置换吗',
        cancelText: '取消',
        confirmText: '确定',
        success: function (res) {
          if(res.confirm){
            self.readmore_confirm()
          }    
        }
      })
    }
    
  },
  readmore_confirm:function(){
    wx.showLoading({
      title: '获取中',
    })
    var self=this
    var data={
       id:self.data.id,
       pay_type:self.data.pay_type,
       from:self.data.from,
       UseId:self.data.MyProjectId,
    }
    // console.log(data)
    // return
     core.post("ReadMorePay",data,function(res){
        //console.log(res)
        wx.hideLoading();
        if(res.code==2){
          wx.requestPayment({
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': 'MD5',
            'paySign': res.data.paySign,
            'success': function (res) {
              self.setData({ is_need_pay:0,pag_flag:false})
            },
            'fail': function (res) {
              wx.showToast({
                'title':'支付失败',
                'icon':'none'
              })
            }
          })
        }else if(res.code==1){
          wx.showToast({
            'title':'获取成功',
            'icon':'success',
            success:function(){
              self.setData({ is_need_pay:0,pag_flag:false})
              self.GetUserInfo()
            }
          })
        }else{
          wx.showToast({
            'title':res.msg,
            'icon':'none'
          })
        }
      })
  },
  /**
   * 打电话
   */
  call:function(){
    var self=this
    wx.makePhoneCall({
      phoneNumber: self.data.data.tel,
    })
  },
  saveImage: function (e) {
    console.log(3333)
    wx.getImageInfo({
      src: this.data.data.qcode,
      success: function (ret) {
          var path = ret.path;
          wx.saveImageToPhotosAlbum({
              filePath: path,
              success(result) {
                wx.showToast({
                  'title':'保存成功',
                  'icon':'success'
                })
              }
          })
      }
    })
   },

   //点击放大图
   previewImg:function(e){
   
    var imgArr = this.data.data.imgs.length>0?this.data.data.imgs:['/static/images/zhanwei.png'];
    wx.previewImage({
      current:this.data.data.imgs,     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  /**
   * 举报
   */
  jubao:function(){
    wx.navigateTo({
      url: '/pages/jubao/index?id='+this.data.id,
    })
  },
  // 显示遮罩层
  showModal: function () {
    var that=this;
    that.setData({
      hideModal:false
    })
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation 
    setTimeout(function(){
      that.fadeIn();//调用显示动画
    },10)   
  },

  // 隐藏遮罩层
  hideModal: function () {
    var that=this; 
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown();//调用隐藏动画   
    setTimeout(function(){
      that.setData({
        hideModal:true
      })      
    },10)//先执行下滑动画，再隐藏模块
    
  },

  //动画集
  fadeIn:function(){
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    })    
  },
  fadeDown:function(){
    this.animation.translateY(600).step()
    this.setData({
      animationData: this.animation.export(),  
    })
  }, 
  radioChange(e) {
    var self=this
    this.setData({
      pay_type: e.detail.value,
    })
    if(this.data.pay_type==1){
      this.setData({
        pay_fee: self.data.data.fee,
      })
    }
    if(this.data.pay_type==3){
      this.setData({
        pay_fee: 0,
      })
    }
    
    
    const checked = e.detail.value
    const changed = {}
    for (let i = 0; i < this.data.radioItems.length; i++) {
      if (this.data.radioItems[i].value == e.detail.value) {
        changed['radioItems[' + i + '].checked'] = true
      } else {
        changed['radioItems[' + i + '].checked'] = false
      }
    }
    this.setData(changed)
  },
  show_pay:function(){
    this.setData({pag_flag:true})
  },
  close_pay:function(){
    this.setData({pag_flag:false})
  },
  /**
   * 获得用户信息
   */
  GetUserInfo:function(){
    var self=this
    core.post("GetUserinfo",{},function(res){
      if(res.code==1){
           self.setData({           
            userinfo:res.data,         
           })
      }
    })
  },
  getMyProjectList:function(){
    var self=this
    core.post("ProjectList",{page:1,is_my:1,status:1,is_change:0},function(res){ 
      if(res.code==1){
          var data=[];
          res.data.forEach((item) => {
            data.push('(可置换：'+item.can_change_num+'次)'+item.title)
          });
          self.setData({MyProject:res.data,MyProjectArr:data})
          if(res.data.length>0){
            self.setData({MyProjectId:res.data[0]['id']})
          }
        }     
    })
    
},
bindPickerChange_hx: function (e) {
  console.log(e)
  this.setData({  
    MyProjectId :this.data.MyProject[e.detail.value].id ,
    MyProjectKey: e.detail.value,  
  })
},
})